package com.xnyzc.lhy.order.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xnyzc.lhy.common.component.config.security.RocketConfig;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.MqConstant;
import com.xnyzc.lhy.common.constant.MqConsumerGroupConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.order.EBillType;
import com.xnyzc.lhy.common.penum.order.ECancelOrderType;
import com.xnyzc.lhy.common.penum.order.EDiDiOrderStatus;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.order.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.order.entity.param.order.OrderDetailParam;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.order.entity.user.message.OaSysMessage;
import com.xnyzc.lhy.order.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.order.service.driver.IOaDUserInfoService;
import com.xnyzc.lhy.order.service.order.IOaCOrderPersonalService;
import com.xnyzc.lhy.order.service.user.message.IOaSysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * 滴滴取消订单
 *
 * @author c
 */
@Slf4j
@Component
public class MqDiDiCancelOrderSyncConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    RocketConfig config;

    @Autowired
    RedisCommon redisCommon;

    @Value("${rocketMq.isStart}")
    private boolean isStart;

    @Autowired
    private IOaDUserInfoService dUserInfoService;

    @Autowired
    private IOaSysMessageService iOaSysMessageService;

    @Autowired
    private IOaCOrderPersonalService personalService;

    @Autowired
    private OaCOrderPersonalMapper personalMapper;

    /**
     * 开启监听
     */
    @PostConstruct
    public void init() {
        try {
            if (!isStart) {
                return;
            }
            consumer = new DefaultMQPushConsumer(MqConsumerGroupConstant.DIDI_CANCEL);
            consumer.setNamesrvAddr(config.getNameServerAddr());
            consumer.subscribe(config.getTopic(), MqConstant.DIDI_CANCEL_ORDER);
            consumer.setConsumeMessageBatchMaxSize(1);
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                    MessageExt messageExt = msgs.get(0);
                    return MqDiDiCancelOrderSyncConsumer.this.dealBody(messageExt);
                }
            });
            consumer.start();
            log.debug("---------司机状态同步消费者启动完成----o(*^▽^*)┛----");
        } catch (Exception e) {
            log.debug("---------司机状态同步消费者初始化失败---(# ﾟДﾟ)--------");
            log.error(e.getMessage());
        }
    }

    /**
     * 处理业务逻辑
     *
     * @param messageExt
     * @return
     */
    public ConsumeConcurrentlyStatus dealBody(MessageExt messageExt) {
        OrderDetailParam orderDetailParam = null;
        try {
            //发送的消息
            String body = new String(messageExt.getBody());
            if (CheckUtil.strIsEmpty(body)) {
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
            orderDetailParam = JSON.parseObject(body, OrderDetailParam.class);

            log.info("乘客取消订单被消费！！参数：{}", orderDetailParam.toString());
            // 查询订单状态
            QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(OaCOrderPersonal.DRIVER_ID, OaCOrderPersonal.PASSENGER_PHONE_SUFFIX);
            queryWrapper.eq(OaCOrderPersonal.ORDER_NO, orderDetailParam.getOrder_id());
            List<OaCOrderPersonal> oaCOrderPersonals = personalMapper.selectList(queryWrapper);
            if (CheckUtil.collectionIsEmpty(oaCOrderPersonals)) {
                throw DiDiException.create(EDiDiErrorCode.orderPersonalSelectFail);
            }
            OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonals.get(0);

            if(oaCOrderPersonal.getDriverId()!=null&&oaCOrderPersonal.getPassengerPhoneSuffix()!=null){
                log.info("查询出来的司机ID为：{}，乘客手机号后四位为：{}", oaCOrderPersonal.getDriverId(), oaCOrderPersonal.getPassengerPhoneSuffix());
            }

            // 修改订单状态
            if (CheckUtil.objIsEmpty(orderDetailParam)) {
                throw DiDiException.create(EDiDiErrorCode.parameterError);
            }
            Date date = new Date();
            // 修改
            UpdateWrapper<OaCOrderPersonal> updateWrapper = new UpdateWrapper<>();
            try {
                updateWrapper.set(OaCOrderPersonal.DIDI_ORDER_STATUS, EDiDiOrderStatus.cancelOrderNoNeedPayment.getDidiType());
                updateWrapper.set(OaCOrderPersonal.ORDER_STATUS, EDiDiOrderStatus.cancelOrderNoNeedPayment.getType());
            } catch (Exception e) {
                throw DiDiException.create(EDiDiErrorCode.notOrderStatus);
            }
            updateWrapper.set(OaCOrderPersonal.CANCEL_ORDER_TIME, date);
            updateWrapper.set(OaCOrderPersonal.UPDATE_TIME, date);
            updateWrapper.set(OaCOrderPersonal.CANCEL_REASON, ECancelOrderType.replyPassengersAfter.getType());
            if (StringUtils.isNotBlank(orderDetailParam.getCancel_reason())) {
                updateWrapper.set(OaCOrderPersonal.CANCEL_REASON_REMARK, orderDetailParam.getCancel_reason());
            }
            updateWrapper.eq(OaCOrderPersonal.ORDER_NO, orderDetailParam.getOrder_id());
            boolean update = personalService.update(updateWrapper);
            log.info("乘客取消订单，是否成功：{}", update);

            String orderNo = orderDetailParam.getOrder_id();
            String key = RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo;
            String keyVeh = RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE + orderNo;
            // 删除redis中的数据，停止接单
            redisCommon.remove(keyVeh);
            redisCommon.remove(key);
            // 释放司机，如果有driverId才释放
            if (CheckUtil.objIsEmpty(oaCOrderPersonal.getDriverId())) {
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
            Long driverId = oaCOrderPersonal.getDriverId();
            // 司机当前订单是否可以释放
            QueryWrapper<OaDUserInfo> dUserWrapper = new QueryWrapper<>();
            dUserWrapper.select(OaDUserInfo.CURRENT_ORDER_NO);
            dUserWrapper.eq(OaDUserInfo.DRIVER_ID, driverId);
            OaDUserInfo one = dUserInfoService.getOne(dUserWrapper);

            // 释放的订单为司机当前订单才释放司机
            if (StringUtils.equals(orderDetailParam.getOrder_id(), one.getCurrentOrderNo())) {
                UpdateWrapper<OaDUserInfo> updateWrapperDUser = new UpdateWrapper<>();
                updateWrapperDUser.set(OaDUserInfo.IS_ORDER, 0);
                updateWrapperDUser.set(OaDUserInfo.CURRENT_ORDER_NO, "");
                updateWrapperDUser.eq(OaDUserInfo.DRIVER_ID, driverId);
                try {
                    boolean updateUser = dUserInfoService.update(updateWrapperDUser);
                    log.info("乘客取消行程释放司机结果：{}", updateUser);
                    log.info("DRIVER_HISTORY 司机被释放了,司机当前订单号:[{}],当前订单状态:[{}],司机ID:[{}]",
                            orderNo,
                            EDiDiOrderStatus.cancelOrderNoNeedPayment.getType(),
                            driverId
                    );
                } catch (Exception e) {
                    log.error("解除司机锁定失败，{}", e);
                }
            }
            if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getPassengerPhoneSuffix())) {
                // 给司机端首页展示消息
                OaSysMessage oaSysMessage = new OaSysMessage();
                oaSysMessage.setMessageType(1);
                oaSysMessage.setPushCode(EBillType.CANCEL_TRIP.getIdenifition());
                oaSysMessage.setMessageContent(MessageConstant.TAILNUMBER + oaCOrderPersonal.getPassengerPhoneSuffix() + MessageConstant.USER_CANCEL_ORDER);
                oaSysMessage.setDriverId(oaCOrderPersonal.getDriverId());
                iOaSysMessageService.saveMessage(oaSysMessage);
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            log.error("{}", e);
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
